<script setup>
import {Phone, Lock} from '@element-plus/icons-vue'
import {getUserInfo,login} from '@/api/auth.js'
import {reactive, ref,onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/store/user.js'
import {ElNotification} from 'element-plus'

const userStore = useUserStore()
const router = useRouter()

const form = reactive({
  phone: '',
  password: '',
})

const formRef = ref(null)

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      console.log('表单验证不通过')
      return
    }
    try {
      const res = await login(form)
      console.log('登录接口返回:', res)

      if (res.code === 200 && res.data?.tokenValue) {
        // 先保存 token
        localStorage.setItem('token', res.data.tokenValue)

        // 再获取完整用户信息
        const userInfoRes = await getUserInfo()
        if (userInfoRes.code === 200) {
          userStore.setUserInfo(userInfoRes.data)
        } else {
          ElNotification.error(userInfoRes.msg || '获取用户信息失败')
        }

        await router.push('/')
      } else {
        ElNotification.error(res.msg || '登录失败')
      }
    } catch (err) {
      ElNotification.error('登录请求失败')
      console.error(err)
    }
  })
}

const pwdValidate = (_, value, callback) => {
  const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/
  if (value.length < 6 || value.length > 20) {
    return callback(new Error('密码长度在6 - 20之间'))
  }
  if (!reg.test(value)) {
    return callback(new Error('密码必须包括大小写字母和数字'))
  }
  callback()
}

const rules = {
  phone: [
    {required: true, message: '请输入电话号', trigger: 'blur'},
    {min: 11, max: 11, message: '电话号长度为11位', trigger: 'blur'},
  ],
  password: [
    {validator: pwdValidate, trigger: 'blur'},
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
}
const userInfo = ref({})

const fetchUserInfo = async () => {
  const { data } = await getUserInfo()
  userInfo.value = data
}
onMounted(() => {
  fetchUserInfo()
})

</script>

<template>
  <div class="login-container">
    <el-form :rules="rules" ref="formRef" :model="form" class="login-form">
      <h2>登录</h2>
      <div class="tips">输入您的账号以继续</div>
      <el-form-item label="账号" prop="phone">
        <el-input v-model="form.phone">
          <template #prefix>
            <el-icon>
              <Phone/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Lock/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  background-image: url('@/assets/login.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;

  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form {
  background: rgba(255, 255, 255, 0.9);
  padding: 2rem;
  border-radius: 0.5rem;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  font-size: 1.25rem;
  color: #2c3e50;
  font-weight: bold;
}

.tips {
  font-size: 0.875rem;
  color: #6b7280;
  margin-top: 0.25rem;
  text-align: center;
  margin-bottom: 1rem;
}

.el-button {
  width: 100%;
}
</style>
